package com.tdam2011.grupo02.messagesender;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class NetworkReceiver extends BroadcastReceiver {

	private static final long REPEAT_TIME = 1000 * 60;
	private static final String TAG = "NetworkReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		Log.d(TAG, "onReceive - " + action);

		if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
			NetworkInfo network = intent
					.getParcelableExtra((ConnectivityManager.EXTRA_NETWORK_INFO));

			AlarmManager service = (AlarmManager) context
					.getSystemService(Context.ALARM_SERVICE);

			Intent intentReceiver = new Intent(context,
					StartUpdateMessagesReceiver.class);

			PendingIntent pending = PendingIntent.getBroadcast(context, 0,
					intentReceiver, PendingIntent.FLAG_CANCEL_CURRENT);

			if (network.isConnected()) {
				Log.d(TAG, "is connectivity");
				startSchedule(service, pending);
				
				startSendOutboxService(context);
				
			} else {
				Log.d(TAG, "is not connectivity");
				stopSchedule(service, pending);

				Intent serviceIntent = new Intent(context,
						StopUpdateMessagesReceiver.class);

				context.sendBroadcast(serviceIntent);
			}
		}
	}

	private void startSchedule(AlarmManager service, PendingIntent pending) {
		if (service != null) {
			// Start 10 seconds after boot completed
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.SECOND, 10);

			// Fetch every 60 seconds
			// InexactRepeating allows Android to optimize the energy
			// consumption
			service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
					cal.getTimeInMillis(), REPEAT_TIME, pending);
		}
	}

	private void stopSchedule(AlarmManager service, PendingIntent pending) {
		if (service != null)
			service.cancel(pending);
	}
	
	private void startSendOutboxService(Context context) {
		Log.d("DEMO", "startSendOutboxService from Receiver");
		Intent msgwOutboxIntent = new Intent(context, SendOutboxIntentService.class);
		context.startService(msgwOutboxIntent);
	}
}
